package org.custom.spring.boot.datasource.config;

import org.custom.spring.boot.datasource.filter.DataSourceFilter;
import org.custom.spring.boot.datasource.interceptor.DynamicDataSourceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Collections;

/**
 * spring-boot-datasource项目配置类
 *
 * @author 李坤
 * @date 2022/3/31 10:05
 */
@Configuration
@ComponentScan({"com.knife"})
@MapperScan("org.custom.spring.boot.*.mapper")
public class DataSourceConfig implements WebMvcConfigurer {

    @Resource
    private DynamicDataSourceInterceptor dynamicDataSourceInterceptor;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    public Validator validator4DataSource() {
        return Validation.buildDefaultValidatorFactory().getValidator();
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();

        filterRegistrationBean.setUrlPatterns(Collections.singletonList("/data/parse/*"));
        filterRegistrationBean.setFilter(new DataSourceFilter());
        filterRegistrationBean.setName("dataSourceFilter");
        filterRegistrationBean.setOrder(1);

        return filterRegistrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(dynamicDataSourceInterceptor);
    }
}
